package com.ruoyi.basedata.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.basedata.domain.TerminalsDb;
import com.ruoyi.basedata.domain.TerminalsXb;
import com.ruoyi.basedata.domain.UserAccount;
import com.ruoyi.basedata.domain.UsersXb;
import com.ruoyi.basedata.domain.vo.UserTerminalsRequestVO;
import com.ruoyi.basedata.domain.vo.UserTerminalsVO;
import com.ruoyi.basedata.mapper.*;
import com.ruoyi.basedata.service.IUsersXbService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 小用户档案Service业务层处理
 *
 * @author ruoyi
 * @date 2023-09-07
 */
@Service
@Slf4j
public class UsersXbServiceImpl implements IUsersXbService
{
    @Autowired
    private UsersXbMapper usersXbMapper;

    @Autowired
    private TerminalsXbMapper terminalsXbMapper;

    @Autowired
    private TerminalsDbMapper terminalsDbMapper;

    @Autowired
    private UserAccountMapper userAccountMapper;




    /**
     * 查询小用户档案
     *
     * @param ID 小用户档案主键
     * @return 小用户档案
     */
    @Override
    public UsersXb selectUsersXbByID(Long ID)
    {
        return usersXbMapper.selectUsersXbByID(ID);
    }

    /**
     * 查询小用户档案列表
     *
     * @param usersXb 小用户档案
     * @return 小用户档案
     */
    @Override
    public List<UsersXb> selectUsersXbList(UsersXb usersXb)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (Objects.equals(user.getSystemFlag(), Constants.SYS_FLAG_NORMAL_USER)){
            usersXb.setTenantId(user.getTenantId());
        }
        if(usersXb.getParams().containsKey("departureTime") && !"".equals(usersXb.getParams().get("departureTime")) ){
            String departureTime = usersXb.getParams().get("departureTime").toString();
            String[] departureTimes = departureTime.split(",");
            if(departureTimes.length==2){
                usersXb.getParams().put("beginDepartureTime", departureTimes[0]);
                usersXb.getParams().put("endDepartureTime",departureTimes[1]);
            }
        }

        return usersXbMapper.selectUsersXbList(usersXb);
    }

    @Override
    public List<UsersXb> selectUsersXbList(Collection<String> userIdList) {
        return usersXbMapper.selectList(new LambdaQueryWrapper<UsersXb>()
                .in(!CollectionUtils.isAnyEmpty(),UsersXb::getUserId,userIdList));
    }

    /**
     * 新增小用户档案
     *
     * @param usersXb 小用户档案
     * @return 结果
     */
    @Override
    public int insertUsersXb(UsersXb usersXb)
    {
        List<UsersXb> usersXbs = usersXbMapper.selectList(new LambdaQueryWrapper<UsersXb>()
                .eq(usersXb.getUserId() != null, UsersXb::getUserId, usersXb.getUserId()));
        if (usersXbs.isEmpty()){
            if(usersXb.getCreateTime() != null){
                usersXb.setCreateTime(DateUtils.getNowDate());
            }
            if(usersXb.getAdmissionTime() != null){
                usersXb.setAdmissionTime(DateUtils.getNowDate());
            }
            if(usersXb.getUserMark() == null) {
                usersXb.setUserMark(1);
            }
            if(usersXb.getUserMark() == 0){
                usersXb.setDepartureTime(DateUtils.getNowDate());
            }
            usersXb.setDelFlag(0);
            //用户新增时，新增一条用户账户记录
            UserAccount userAccount = UserAccount.builder()
                    .userId(usersXb.getUserId())
                    .monthArrear(BigDecimal.valueOf(0L))
                    .lateFee(BigDecimal.valueOf(0L))
                    .totalArrear(BigDecimal.valueOf(0L))
                    .monthCost(BigDecimal.valueOf(0L))
                    .settleBalance(BigDecimal.valueOf(0L))
                    .availableBalance(BigDecimal.valueOf(0L))
                    .updatedTime(DateUtils.getNowDate())
                    .build();
            userAccountMapper.insert(userAccount);
            return usersXbMapper.insert(usersXb);// .insertUsersXb(usersXb);
        }
        return 0;
    }

    /**
     * 修改小用户档案
     *
     * @param usersXb 小用户档案
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUsersXb(UsersXb usersXb) {
        UsersXb exist = usersXbMapper.selectOne(new LambdaQueryWrapper<UsersXb>()
                .eq(UsersXb::getUserId, usersXb.getUserId()));
        if (exist == null) {
            UsersXb beforeUpdate = usersXbMapper.selectById(usersXb.getId());
            int rows = usersXbMapper.updateUsersXb(usersXb);
            if (rows > 0) {
                // 同步修改大表档案里的user_id
                LambdaQueryWrapper<TerminalsDb> dbUpdateWrapper = Wrappers.lambdaQuery();
                dbUpdateWrapper.eq(TerminalsDb::getUserId, beforeUpdate.getUserId());
                TerminalsDb dbUpdate = new TerminalsDb();
                dbUpdate.setUserId(usersXb.getUserId());
                terminalsDbMapper.update(dbUpdate, dbUpdateWrapper);
                // 同步修改小表档案里的user_id
                LambdaQueryWrapper<TerminalsXb> xbUpdateWrapper = Wrappers.lambdaQuery();
                xbUpdateWrapper.eq(TerminalsXb::getUserId, beforeUpdate.getUserId());
                TerminalsXb xbUpdate = new TerminalsXb();
                xbUpdate.setUserId(usersXb.getUserId());
                terminalsXbMapper.update(xbUpdate, xbUpdateWrapper);
                // 同步修改用户账户表里的user_id
                LambdaQueryWrapper<UserAccount> acUpdateWrapper = Wrappers.lambdaQuery();
                acUpdateWrapper.eq(UserAccount::getUserId, beforeUpdate.getUserId());
                UserAccount acUpdate = UserAccount.builder().userId(usersXb.getUserId()).build();
                userAccountMapper.update(acUpdate, acUpdateWrapper);
            }
            return rows;
        }
        if (Objects.equals(exist.getId(), usersXb.getId())) {
            if(exist.getUserMark() != usersXb.getUserMark()){
                if(usersXb.getUserMark() == 0){
                    usersXb.setDepartureTime(DateUtils.getNowDate());
                }else {
                    usersXb.setAdmissionTime(DateUtils.getNowDate());
                }
            }
            return usersXbMapper.updateById(usersXb);//updateUsersXb(usersXb);
        }
        return 0;
    }

    /**
     * 批量删除小用户档案
     *
     * @param IDs 需要删除的小用户档案主键
     * @return 结果
     */
    @Override
    public int deleteUsersXbByIDs(Long[] IDs)
    {
        // List<Long> deleteList = new ArrayList<>();
        // Arrays.stream(IDs).forEach(id ->{
        //     Integer count = terminalsXbMapper.countByUserId(id);
        //     if (count == 0){
        //         deleteList.add(id);
        //     }
        // });
        // if (deleteList.size()==0){
        //     return 0;
        // }
        //更改为逻辑删除
        for (Long id : IDs) {
            UsersXb usersXb = new UsersXb();
            usersXb.setId(id);
            usersXb.setDelFlag(2);
            usersXbMapper.updateById(usersXb);
        }
//        return usersXbMapper.deleteBatchIds(Arrays.asList(IDs));
        return 1;
    }

    /**
     * 删除小用户档案信息
     *
     * @param ID 小用户档案主键
     * @return 结果
     */
    @Override
    public int deleteUsersXbByID(Long ID)
    {
        //更改为逻辑删除
        LambdaQueryWrapper<UsersXb> upWrapper = Wrappers.lambdaQuery();
        upWrapper.eq(UsersXb::getId, ID);
        UsersXb usersXb = new UsersXb();
        usersXb.setDelFlag(2);
        return usersXbMapper.update(usersXb,upWrapper);
//        return usersXbMapper.deleteById(ID);
    }

    @Override
    public String importUser(List<UsersXb> list, boolean updateSupport, String operName) {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (UsersXb usersXb : list)
        {
            try
            {
                // 验证是否存在这个表用户
                List<UsersXb> usersXbList = usersXbMapper.selectList(new LambdaQueryWrapper<UsersXb>()
                        .eq(UsersXb::getUserId, usersXb.getUserId()));
                if(null != usersXbList && usersXbList.size()>0){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、用户编号 " + usersXb.getUserId() + " 已存在");
                }else {
                    usersXb.setCreateTime(DateUtils.getNowDate());
                    usersXb.setUserMark(1);
                    usersXb.setDelFlag(0);
                    usersXbMapper.insertUsersXb(usersXb);
                    //用户新增时，新增一条用户账户记录
                    UserAccount userAccount = UserAccount.builder()
                            .userId(usersXb.getUserId())
                            .monthArrear(BigDecimal.valueOf(0L))
                            .lateFee(BigDecimal.valueOf(0L))
                            .totalArrear(BigDecimal.valueOf(0L))
                            .monthCost(BigDecimal.valueOf(0L))
                            .settleBalance(BigDecimal.valueOf(0L))
                            .availableBalance(BigDecimal.valueOf(0L))
                            .updatedTime(DateUtils.getNowDate())
                            .build();
                    userAccountMapper.insert(userAccount);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、用户编号 " + usersXb.getUserId() + " 更新成功");
                }

            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、用户编号 " + usersXb.getUserId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 获取该用户的设备、与该用户相关公摊生产设备、与该用户相关公摊消费用户的设备
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> getUserTerminalList(String userId) {
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("OwnUserTerminalList", null);
        resMap.put("publicTerminalList", null);
        resMap.put("publicUserTerminalList", null);
        //查找用户下所有关联的设备
        List<UserTerminalsVO> list = usersXbMapper.getOwnUserTerminalList(userId);
        //查找该用户影响公摊的生产设备
        List<UserTerminalsVO> list2 = usersXbMapper.getpublicTerminalList(userId);
        //查找该用户影响公摊的消费用户设备
        List<UserTerminalsVO> list3 = usersXbMapper.getpublicUserTerminalList(userId);

        resMap.put("OwnUserTerminalList", list);
        resMap.put("publicTerminalList", list2);
        resMap.put("publicUserTerminalList", list3);
        return resMap;
    }

    /**
     * 用户离场时，单独更新离场时间
     * @param userId
     * @param departureTime
     */
    @Override
    public void updateUserForLeveOnDepartureTime(String userId,String departureTime){
        UsersXb exist = usersXbMapper.selectOne(new LambdaQueryWrapper<UsersXb>()
                .eq(UsersXb::getUserId, userId));
            exist.setDepartureTime(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",departureTime));
        usersXbMapper.updateById(exist);//updateUsersXb(usersXb);
    }

    /**
     * 用户离场时，单独更新离场状态
     * @param userId
     */
    @Override
    public void updateUserForLeveOnUserMark(String userId){
        UsersXb exist = usersXbMapper.selectOne(new LambdaQueryWrapper<UsersXb>()
                .eq(UsersXb::getUserId, userId));
        exist.setUserMark(0);
        exist.setLeaveBillStatus(1);
        usersXbMapper.updateById(exist);//updateUsersXb(usersXb);
    }

}
